﻿#if NETCOREAPP3_0
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
#else
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
#endif
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Collections.Specialized;
using System.Net;
using System.Threading.Tasks;

namespace Longbow.Web
{
    /// <summary>
    /// 统一异常处理过滤器
    /// </summary>
    public class ExceptionFilter : IAsyncExceptionFilter
    {
#if NETCOREAPP3_0
        private readonly IWebHostEnvironment _env;
#else
        private readonly IHostingEnvironment _env;
#endif
        private readonly ILogger<ExceptionFilter> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="env"></param>
        /// <param name="logger"></param>
#if NETCOREAPP3_0
        public ExceptionFilter(IWebHostEnvironment env, ILogger<ExceptionFilter> logger)
#else
        public ExceptionFilter(IHostingEnvironment env, ILogger<ExceptionFilter> logger)
#endif
        {
            _env = env;
            _logger = logger;
        }

        /// <summary>
        /// 异常发生时调用此方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (!_env.IsDevelopment())
            {
                var nv = new NameValueCollection
                {
                    ["ErrorPage"] = context.HttpContext.Request.Path,
                    ["UserIp"] = context.HttpContext.Connection.RemoteIpAddress.ToIPv4String(),
                    ["UserId"] = context.HttpContext.User.Identity.Name
                };
                _logger.Log(LogLevel.Error, new EventId(0), nv, context.Exception, (t, e) => string.Empty);
                context.ExceptionHandled = true;
                if (context.HttpContext.Request.Path.StartsWithSegments("/api")) context.Result = new JsonResult(new { message = context.Exception.Message, error = context.Exception.GetType().FullName });
                else context.Result = new StatusCodeResult(500);
            }
            return Task.CompletedTask;
        }
    }
}
